package com.spring.authManage.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.spring.authManage.dao.ResourceInfoDao;
import com.spring.authManage.dao.UserInfoDao;
import com.spring.authManage.pojo.ResourceInfo;
import com.spring.authManage.pojo.UserInfo;
import com.spring.authManage.pojo.UserRoleInfo;
import com.spring.authManage.service.UserInfoService;
import com.spring.common.util.ChunQiuTool;
import com.spring.common.util.MD5;

/**
 * 用户管理，用户权限分配service层实现
 *
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService{

	@Autowired
	private UserInfoDao userInfoDao;
	@Autowired
	private ResourceInfoDao resourceInfoDao;
	
	/**
	 * 添加用户信息
	 * @param info
	 * @throws Exception 
	 */
	public String addUserInfo(UserInfo info) throws Exception {
		String error = checkform(info);
		info.setUserName(info.getUserName().trim());
		info.setRealName(info.getRealName().trim());
		String result = "";
		if(error.equals("")){
			this.userInfoDao.addUserInfo(info);
		result = "Y";
		} else {
			result = error;
		}
		return result;
	}
	
	/**
	 * 更新用户信息
	 * @param info
	 * @throws Exception 
	 */
	public String updateUserInfo(UserInfo info) throws Exception {
		String error = checkform(info);
		info.setUserName(info.getUserName().trim());
		info.setRealName(info.getRealName().trim());
		String result = "";
		if(error.equals("")){
			this.userInfoDao.updateUserInfo(info);
			result = "Y";
		} else {
			result = error;
		}
		return result;
	}
	/**
	 * 根据用户ID获取用户信息
	 * @param userName
	 * @return
	 */
	public UserInfo queryUserInfoByUserId(String userId) throws Exception {
		return this.userInfoDao.queryUserInfoByUserId(userId);
	}
	/**
	 * 根据用户账号获取用户信息
	 * @param userName
	 * @return
	 */
	public UserInfo queryUserInfoByUserName(String userName) throws Exception {
		return this.userInfoDao.queryUserInfoByUserName(userName);
	}
	/**
	 * 根据角色名称获取拥有该角色的所有用户
	 * @param roleName
	 * @return
	 */
	public UserInfo queryUserInfosByRoleName(String roleName) throws Exception {
		UserInfo info = new UserInfo();
		info.setRoleName(roleName);
		return this.userInfoDao.queryUserInfoByParam(info);
	}
	/**
	 * 更新用户权限
	 * @param info
	 */
	public void updateUserRole(String userId, String roleIds,String updateUser) throws Exception {
		this.userInfoDao.deleteUserRoles(userId);
		if(!roleIds.equals("")){
			List<UserRoleInfo>list = new ArrayList<UserRoleInfo>();
			String[] roles = roleIds.split(",");
			
			for(String roleId:roles){
				UserRoleInfo info = new UserRoleInfo();
				info.setUserId(userId);
				info.setUpdateUser(updateUser);
				
				if(!"".equals(roleId)&&roleId!=null){
					info.setRoleId(roleId);
					list.add(info);
				}
			}
			
			this.userInfoDao.addUserRoles(list);
		}
	}
	/**
	 * 根据查询条件获取符合条件的用户信息
	 * @param param
	 * @return
	 */
	public UserInfo queryUserInfoByParam(UserInfo userInfo) throws Exception {
		return this.userInfoDao.queryUserInfoByParam(userInfo);
	}
	/**
	 * 根据user_id获取用户角色
	 * @param user_id
	 * @return
	 */
	public List<UserRoleInfo> queryUserRoleInfoByUserId(String user_id) throws Exception {
		return userInfoDao.queryUserRoleInfoByUserId(user_id);
	}
	
	/**
	 * 重置密码
	 * 
	 * @param userInfo
	 * @return String
	 */
	public void resetPwd(String id,String password) throws Exception {
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("password", password);
		map.put("id", id);		
		this.userInfoDao.resetPwd(map);
	}
	
	/**
	 * 修改后台登陆用户密码
	 * 
	 * @param userInfo
	 * @return String
	 */
	public String updatePwd(Map<String,Object> map) throws Exception {
		String result = "";
		String error = checkPwd(map); 
		if(error.equals("")){
			//密码转换加密
			map.put("password_old", MD5.getMD5Encode(ChunQiuTool.convertNull(map.get("password_old"))));
			map.put("password_new", MD5.getMD5Encode(ChunQiuTool.convertNull(map.get("password_new"))));
			int r=this.userInfoDao.updatePwd(map);
			result = r>0 ?"Y":"密码错误";
		} else {
			result = error;
		}
		return result;
	}
	
	/**
	 * 格式检查后台，检查是否有重复资源
	 * @param resourceInfo
	 * @return
	 */
	private String checkform(UserInfo info) throws Exception {
		String error = "";
		if ("".equals(ChunQiuTool.convertNull(info.getUserName()))) {
			error = "用户名不能为空！";
		} else if (ChunQiuTool.convertNull(info.getUserName()).length() > 20) {
			error = "用户名不能长于20！";
		} else if ("".equals(ChunQiuTool.convertNull(info.getRealName()))) {
			error = "真实名不能为空！";
		} else if (ChunQiuTool.convertNull(info.getRealName()).length() > 50) {
			error = "真实名不能长于50！";
		} 
		else {
			Integer checkDouble = this.userInfoDao.countExistUserByUserName(info);
			if(checkDouble != 0 ) {
				error = "用户名重名";
			}
		}
		return error;
	}
	
	/**
	 * 密码格式检查，旧密码核对
	 * @param resourceInfo
	 * @return
	 */
	private String checkPwd(Map<String,Object> map) throws Exception {
		String error = "";
		String pwdOld=ChunQiuTool.convertNull(map.get("password_old"));
		String pwdNew=ChunQiuTool.convertNull(map.get("password_new"));
		String pwdConfirm=ChunQiuTool.convertNull(map.get("password_confirm"));
		if ("".equals(pwdOld)) {
			error = "旧密码不能为空！";
		}  else if ("".equals(ChunQiuTool.convertNull(pwdNew))) {
			error = "新密码不能为空！";
		}  else if (!ChunQiuTool.convertNull(pwdConfirm).equals(ChunQiuTool.convertNull(pwdNew))) {
			error = "两次密码输入需一致";
		} 
		String regex =  "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
		if (!ChunQiuTool.convertNull(pwdNew).matches(regex)){
			error = "密码格式为字母和数字组合且长度在8到16位！";
		}		
		return error;
	}
	
	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	public void deleteUser(String id) throws Exception {
		this.userInfoDao.deleteUser(id);
	}
	/**
	 * 重启用户
	 * @param id
	 * @return
	 */
	public void restartUser(String id) throws Exception {
		this.userInfoDao.restartUser(id);
	}	

	/**
	 * 动态生成菜单
	 * @param param
	 * @return
	 */
	public Object[] getMenuByUserName(String userName) throws Exception{
		Object[] results=new Object[2];
		StringBuffer menuSb = new StringBuffer();
		List<String> tabsName=new ArrayList<String>();
		Map<String, List<ResourceInfo>> menuMap = new LinkedHashMap<String, List<ResourceInfo>>();
//		Map<String, List<ResourceInfo>> menuMap = new HashMap<String, List<ResourceInfo>>();
		List<ResourceInfo> menuInfo = resourceInfoDao.getFirstTextByUserName(userName);
		String firstMenu = "";
		if (menuInfo != null && menuInfo.size() > 0) {
			for (ResourceInfo rInfo : menuInfo) {
				firstMenu = rInfo.getFirst_menu();
//			for (int i=menuInfo.size()-1;i>=0;i--) {
//				ResourceInfo rInfo = new ResourceInfo();
//				rInfo = menuInfo.get(i);
				firstMenu = rInfo.getFirst_menu();
				if (menuMap.containsKey(firstMenu)) {
					List<ResourceInfo> set = menuMap.get(firstMenu);
					set.add(rInfo);
				} else {
					List<ResourceInfo> list = new ArrayList<ResourceInfo>();
					list.add(rInfo);
					menuMap.put(firstMenu, list);
				}
			}
			Iterator<String> iter = menuMap.keySet().iterator();
			int i=1;
			//后端封装json对象时，最外层不要有【】 ，否则js无法识别，【】需要js手工指定
			while(iter.hasNext()){
				firstMenu= iter.next();
				menuSb.append("{");//1
				menuSb.append("id:'").append(firstMenu).append("',");
				menuSb.append("menu:").append("[{");		//2		
				menuSb.append("text : '"+firstMenu+"',");
				menuSb.append("items:[");//3
				List<ResourceInfo> list = menuMap.get(firstMenu);
				Iterator<ResourceInfo> it = list.iterator();
				while(it.hasNext()){
					ResourceInfo rInfo = it.next();
					if(!Strings.isNullOrEmpty(rInfo.getSecond_menu())){
						menuSb.append("{");
						menuSb.append("id:'").append(i++).append("',");
						menuSb.append("text:'").append(rInfo.getSecond_menu()).append("',");
						menuSb.append("href:'").append(rInfo.getUrl().substring(1)).append("'");						
						menuSb.append("}");
						if (it.hasNext()){
							menuSb.append(",");
						}
					}
				}
				menuSb.append("]");
				menuSb.append("}]");//2				
				menuSb.append("}");//1
				if (iter.hasNext()){
					menuSb.append(",");
				}
				//Tab 页名称
				tabsName.add(firstMenu);
			} 
		}
		results[0]=tabsName;
		results[1]=menuSb.toString();
		return results;
	}
}
